"""
@Time: 2021/3/20 下午 9:12
@Author: jinzhuan
@File: baidu.py
@Desc: 
"""
import sys
sys.path.append('/data/zhuoran/code/cognlp')
sys.path.append('/data/zhuoran/cognlp')

import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import RandomSampler

torch.cuda.set_device(5)
device = torch.device('cuda:5')

from cognlp import *
from cognlp.models.re.bert_re_entity import Bert4ReEntity

from cognlp.io.loader.re.baidu import BaiduRelationLoader
from cognlp.io.processor.re.baidu import BaiduRelationProcessor

loader = BaiduRelationLoader()
train_data, dev_data, test_data = loader.load_all('../../../cognlp/data/re/baidu/data')
processor = BaiduRelationProcessor(label_list=loader.get_labels(), path='../../../cognlp/data/re/baidu/data')

vocabulary = Vocabulary.load('../../../cognlp/data/re/baidu/data/vocabulary.txt')

train_datable = processor.process(train_data)
train_dataset = DataTableSet(train_datable, device=device)
train_sampler = RandomSampler(train_dataset)

dev_datable = processor.process(dev_data)
dev_dataset = DataTableSet(dev_datable, device=device)
dev_sampler = RandomSampler(dev_dataset)

# test_datable = processor.process(test_data)
# test_dataset = DataTableSet(test_datable)
# test_sampler = RandomSampler(test_dataset)

model = Bert4ReEntity(len(vocabulary), bert_model='hfl/chinese-roberta-wwm-ext')
metric = ClassifyFPreRecMetric(vocabulary)
loss = nn.CrossEntropyLoss(ignore_index=0)
optimizer = optim.Adam(model.parameters(), lr=0.00002)
# 91.0763
trainer = Trainer(model,
                  train_dataset,
                  dev_data=dev_dataset,
                  n_epochs=20,
                  batch_size=20,
                  loss=loss,
                  optimizer=optimizer,
                  scheduler=None,
                  metrics=metric,
                  train_sampler=train_sampler,
                  dev_sampler=dev_sampler,
                  drop_last=False,
                  gradient_accumulation_steps=1,
                  num_workers=5,
                  save_path="../../../cognlp/data/re/baidu/model",
                  save_file=None,
                  print_every=None,
                  scheduler_steps=None,
                  validate_steps=None,
                  save_steps=None,
                  grad_norm=None,
                  use_tqdm=True,
                  device=device,
                  device_ids=[5],
                  callbacks=None,
                  metric_key=None,
                  writer_path='../../../cognlp/data/re/baidu/tensorboard',
                  fp16=False,
                  fp16_opt_level='O1',
                  checkpoint_path=None,
                  task='paper',
                  logger_path='../../../cognlp/data/re/baidu/logger')

trainer.train()

